package org.example.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.commonapi.domain.CourseResource;
import org.example.commonapi.domain.R;
import org.example.commonapi.util.FileUtil;
import org.example.commonapi.util.oss.OssService;
import org.example.course.service.CourseResourceService;
import org.example.course.until.CourseUntil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/course")
@Slf4j
public class CourseResourcesController {

    @Resource
    CourseResourceService courseResourceService;

    @Resource
    OssService ossService;
    /**
     * 查询课程资源
     * @param courseId
     * @return
     */
    @GetMapping("/list/resources/{courseId}")
    public R listResources(@PathVariable Long courseId,String resourceName) {
        LambdaQueryWrapper<CourseResource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseResource::getCourseId, courseId);
//        判断是否为空
        if(resourceName!=null)
                queryWrapper.like(CourseResource::getName,resourceName);
        List<CourseResource> list=courseResourceService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 上传资源文件
     * @param file
     * @return
     */
    @PostMapping("/upload/resources/{courseId}")
    public R insertResources(@PathVariable Long courseId,@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return R.error("文件不能为空");
        }
        CourseResource courseResource=new CourseResource();
        if(FileUtil.getFileType(file)==null)return R.error("暂不支持该文件类型");
        else courseResource.setType(FileUtil.getFileType(file));
//        判断资源是否合法
        courseResource.setCourseId(courseId);
//        初始化对象
        String size = FileUtil.formatSize(file.getSize());
        courseResource.setSize(size);
        courseResource.setName(file.getOriginalFilename());
        String fileLink=ossService.upload(file);
        courseResource.setLink(fileLink);
        courseResource.setCreateTime(LocalDateTime.now());
//        进行添加资源
        courseResourceService.save(courseResource);
        return R.success();
    }

    /**
     * 删除资源文件
     * @return
     */
    @DeleteMapping("/delete/resources")
    public R deleteResources(@RequestBody List<Long> ids) {
//        删除资源数组
        courseResourceService.removeBatchByIds(ids);
        return R.success();
    }


    @PostMapping("/uploadCourseResources")
    public R uploadCourseResources(@RequestPart("file") List<MultipartFile> files) {
        System.out.println("接收到了文件");
        for (MultipartFile file : files) {
            System.out.println("收到了" + file);
        }
        return R.success();
    }

}
